package com.prj.ufdm.web.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
/**
 * Description: 调用接口通用方法
 * @author   
 * @date 2019年8月21日
 */
@Service
public class RestTemplateUtil {
	
	@Autowired
	RestTemplate restTemplate;
	
    /**
     * Description: 通过POST参数调用接口
     * @param url
     * @param paramMap
     * @param headMap
     * @return 返回 JSONobject
     * @author 
     * @date 2019年8月21日
     * @version 1.0
     */
    public ResponseEntity<JSONObject> doParamPostForJSONobject(String url,Map<String,String> paramMap,Map<String,String> headMap) {
		MultiValueMap<String, String> multiMap = new LinkedMultiValueMap<String, String>();
		if(paramMap!=null) {
			Set<String> paramKey = paramMap.keySet();
			Iterator<String> paramIt = paramKey.iterator();
			while(paramIt.hasNext()){
				String tempKey = paramIt.next();
				String tempValue = paramMap.get(tempKey)!=null ? paramMap.get(tempKey) : "";
				multiMap.add(tempKey,tempValue);
			}
		}
        HttpHeaders header = new HttpHeaders();
        // 需求需要传参为form-data格式
        header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		if(headMap!=null) {
			Set<String> headKey = headMap.keySet();
			Iterator<String> headIt = headKey.iterator();
			while(headIt.hasNext()){
				String tempKey = headIt.next();
				String tempValue = headMap.get(tempKey)!=null ? headMap.get(tempKey) : "";
				header.add(tempKey,tempValue);
			}
		}
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(multiMap, header);
        ResponseEntity<JSONObject> responseJson = restTemplate.exchange(url,HttpMethod.POST,httpEntity,JSONObject.class);
        return responseJson;
    }

    
}
